﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace FreeFlow.Administration
{
  /// <summary>
  /// Details of a WF workflow
  /// </summary>
  public class Workflow : DatabaseAware, IDeletable
  {
    internal Workflow(Server server, IDataReader reader) : base(server)
    {
      name = reader["eWorkflowName"].ToString();
      guid = new Guid(reader["eWorkflowGuid"].ToString());
    }

    private string name;
    /// <summary>
    /// Gets the name of the workflow.
    /// </summary>
    public string Name
    {
      get { return name; }
    }

    private Guid guid;
    /// <summary>
    /// Gets the GUID that uniquely identifies the workflow.
    /// </summary>
    public Guid Guid
    {
      get { return guid; }
    }

    private WorkflowVersionCollection versions;
    /// <summary>
    /// Gets the versions of this workflow that have been published.
    /// </summary>
    public WorkflowVersionCollection Versions
    {
      get 
      {
        if (versions == null)
          versions = new WorkflowVersionCollection(Server, this);
        return versions; 
      }
    }

    #region IDeletable Members

    /// <summary>
    /// Deletes this workflow from the database.
    /// </summary>
    public void Delete()
    {
      using (IDbTransaction transaction = Server.BeginTransaction())
      {
        Server.ExecuteNonQuery(transaction,
          string.Format("DELETE FROM eMSWorkflowDefinition WHERE eWorkflowName ='{0}'",
          SqlEscape(name)));
        Server.ExecuteNonQuery(transaction,
          string.Format("DELETE FROM eMSWorkflow WHERE eWorkflowName ='{0}'",
          SqlEscape(name)));
        transaction.Commit();
      }
    }

    #endregion
  }
}
